<?php

require_once (fvSite::$fvConfig->get("path.entity") . 'loginhistory.class.php') ;

class LoginHistoryManager extends fvRootManager {
	
	protected function __construct () {
	    $objectClassName = substr(__CLASS__, 0, -7);
	    
	    $this->rootObj = new $objectClassName();
	}
	
    static function getInstance()
    {
        static $instance; 
        if (!isset($instance)) {
            $instance = new self();
        }  
        return $instance;
    }

    public function checkLogin($LoggedUserKey) {
        $u = new User();
        
        $query = "select u.* from " . $this->rootObj->getTableName() . " uh
        left join " . $u->getTableName() . " u on (uh.user_id = u.id)
        where login_key = ? AND logged_at > DATE_SUB(NOW(), INTERVAL 30 MINUTE)";
        
        $res = fvSite::$DB->query($query, array($LoggedUserKey));
        
        if (!DB::isError($res)) {
            if (!is_array($row = $res->fetchRow())) return false;
            $User = new User();
            $User->hydrate($row);
        }
        
        if ($User instanceof User)
            return $User;
        else return false;
    }
    
    public function logout($LoggedUserKey) {
        $query = "delete from " . $this->rootObj->getTableName() . " where login_key = ?";
        
        $res = fvSite::$DB->query($query, array($LoggedUserKey));

        if (!DB::isError($res)) {
            return true;
        }
        
        return false;
    }
    
    public function gc() {
        $threshold = rand(0, 100);

        if ($threshold > 50) {
            $query = "delete from " . $this->rootObj->getTableName() . " where logged_at < DATE_SUB(NOW(), INTERVAL 30 MINUTE)";
            $res = fvSite::$DB->query($query);
        }
    }
}
